<?php

# disposed

# http://projects:8081/cdapp-2kt-api/api/hours_personal_query.php

include_once './_portal.php';

const CELL_LEVEL_TAGS = [
  'full' => [
    [0, '序号'], [1, '年月'], [2, '姓名'], [3, '等级'], [4, '资质'],
    [5, '持照'], [6, '席位'], [7, '扇区'], [8, '岗位'], [9, '角色'],
    [10, '开始时间'], [11, '结束时刻'], [12, '分钟数（昼间）'], [13, '分钟数（晚间）'], [14, '分钟数（夜间）'],
    [15, '分钟数'], [16, '小时数'], [17, '小时数（原）'], [18, '单价'], [19, '费用'],
    [23, '点数'], [24, '未知'],
  ],
  'lite' => [
    [0, '序号'], [2, '姓名'], [7, '扇区'], [8, '岗位'], [9, '角色'],
    [10, '开始时间'], [11, '结束时刻'], [15, '分钟数'], [16, '小时数'],
  ],
  'samll' => [
    [0, '#'], [1, 'month'], [2, 'name'], [3, 'column'], [4, 'rank'],
    [5, 'license'], [6, 'seat'], [7, 'sector'], [8, 'post'], [9, 'role'],
    [10, 'begin'], [11, 'end'], [12, 'minutesDaytime'], [13, 'minutesEvening'], [14, 'minutesNight'],
    [15, 'minutes'], [16, 'hours'], [17, 'hoursRaw'], [18, 'wage'], [19, 'salary'],
    [23, 'ratio'], [24, 'unknown'],
  ],
  'mini' => [
    [2, 'name'], [7, 'sector'], [8, 'post'], [9, 'role'],
    [10, 'begin'], [11, 'end'], [16, 'hours'],
  ],
  'tiny' => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 23, 24],
  'micro' => [2, 7, 8, 9, 10, 11, 12, 15, 16],
];

const MAX_TRY_COUNT = 10;

$month = $_GET["month"];
$useridx = $_GET["useridx"];
$column = isset($_GET['column']) ? $_GET['column'] : 'mini';

main($month, $useridx, $column);

function main($month, $useridx, $column) {
  $t = timestamp();
  $userlist = get_param('ATCOSUsers');
  $user = $userlist[$useridx];
  $orgid = $user['office'] == '管制一室' ? 12 : 13;
  $userid = $user['number'];
  $username = $user['name'];
  $data = [];
  $result = '';
  $try_count = 0;
  while (count($data) == 0 && $try_count < MAX_TRY_COUNT) {
    $session_id = get_session();
    query_result($month, $orgid, $userid, $session_id);
    $result = get_result($session_id);
    $data = fetch_data($result, $column);
    $try_count++;
  }
  output([
    'duration' => timestamp() - $t . 'ms',
    'month' => $month,
    'user' => $username,
    'count' => count($data),
    'data' => $data,
    'raw' => $result,
    'url' => "http://172.22.107.22/WebReport/ReportServer?op=fr_view&cmd=view_content&sessionID={$session_id}&reportIndex=0",
  ]);
  exit();
}

function get_session() {
  $curl = curl_init();
  curl_setopt_array($curl, array(
    CURLOPT_URL => 'http://172.22.107.22/WebReport/ReportServer?reportlet=%25E6%2596%25B0%25E7%2589%2588_%25E7%25AE%25A1%25E5%2588%25B6%25E6%25B4%25A5%25E8%25B4%25B4%25E4%25B8%25AA%25E4%25BA%25BA%25E6%258A%25A5%25E8%25A1%25A8.cpt&op=view&userId=19&orgId=4',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'GET',
  ));
  $response = curl_exec($curl);
  curl_close($curl);
  $pattern = "/FR\.SessionMgr\.register\('(\d*)', contentPane\);/";
  preg_match($pattern, $response, $matches);
  $session = (int)$matches[1];
  return $session;
}

function query_result($month, $org_id, $user_ids, $session_id) {

  /*
  {
  "SEARCHYM": "2022-08",
  "ORGID": 13,
  "USERID2": "20120039,20160039,..."
  }
   */

  $params = ['SEARCHYM' => $month, 'ORGID' => $org_id, 'USERID2' => $user_ids];
  $parameters = urlencode(json_stringify($params));
  $curl = curl_init();
  curl_setopt_array($curl, array(
    CURLOPT_URL => "http://172.22.107.22/WebReport/ReportServer?op=fr_dialog&cmd=parameters_d&sessionID={$session_id}",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => "__parameters__={$parameters}",
    CURLOPT_HTTPHEADER => array(
      'Content-Type: application/x-www-form-urlencoded',
    ),
  ));
  $response = curl_exec($curl);
  curl_close($curl);
  return $response;
}

function get_result($session_id) {
  $curl = curl_init();
  curl_setopt_array($curl, array(
    CURLOPT_URL => "http://172.22.107.22/WebReport/ReportServer?op=fr_view&cmd=view_content&sessionID={$session_id}&reportIndex=0",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 20,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'GET',
  ));
  $response = curl_exec($curl);
  curl_close($curl);
  $response = iconv("gbk", "utf-8//ignore", $response);
  return $response;
}

function fetch_data($html, $column) {
  $data = [];
  $tags = CELL_LEVEL_TAGS[$column];
  $html = preg_replace('~<([a-z]+?)\s+?.*?>~i', '<$1>', $html);
  $tr = explode('<tr>', explode('<tbody>', $html)[5]);
  foreach ($tr as $tr_) {
    $td = explode('<td>', $tr_);
    if (count($td) == 26) {
      $row = [];
      foreach ($tags as $i) {
        $val = gettype($i) == 'integer' ? $td[$i + 1] : $td[$i[0] + 1];
        $val = preg_replace("/\<[a-z]*\>/", '', $val);
        $val = preg_replace("/\<\/[a-z]*\>/", '', $val);
        $val = trim($val);
        $val = is_numeric($val) ? (float)$val : $val;
        gettype($i) == 'integer' ? $row[] = $val : $row[$i[1]] = $val;
      }
    }
  }
  return $data;
}